#!/usr/bin/python
from os import listdir, path
import re

max_depth = 5
excludes = ['引用', '目录.md', 'SUMMARY.md', 'update_index.py', 'interview']

def IsExclude(file_name: str):
    for exclude_item in excludes:
        if len(re.findall(exclude_item, file_name)) > 0:
            return True
    return False

def UpdateIndexInner(dir, index_file, depth=1):
    if depth == max_depth + 1:
        return

    curr_files = []
    curr_sub_dirs = []

    dir_entrys = listdir(dir)
    for dir_entry in dir_entrys:
        if path.isfile(path.join(dir,dir_entry)):
            if not IsExclude(dir_entry):
                curr_files.append(dir_entry)
        else:
            if not IsExclude(dir_entry):
                curr_sub_dirs.append(dir_entry)
    if depth == 1 or depth == 2:
        module_name = ''
        module_name_prefix = '## '
        module_name_subfix = '模块'
        if path.basename(dir) == '.':
            module_name = module_name_prefix + 'normal' + module_name_subfix
        else:
            module_name = module_name_prefix + path.basename(dir) + module_name_subfix
        index_file.write(module_name)
        index_file.write('\n')
    
    index_item_template = '- [${index_name}](${index_url})'
    for file_item in curr_files:
        file_name, file_subfix = file_item.split('.')
        index_item = index_item_template.replace('${index_name}', file_name)\
            .replace('${index_url}', dir + '/' + file_item)
        index_file.write(index_item)
        index_file.write('\n')
    

    for sub_dir in curr_sub_dirs:
        UpdateIndexInner(dir + "/" + sub_dir, index_file, depth+1)

def UpdateSummaryInner(dir, index_file, depth=1):
    if depth == max_depth + 1:
        return

    curr_files = []
    curr_sub_dirs = []

    dir_entrys = listdir(dir)
    for dir_entry in dir_entrys:
        if path.isfile(path.join(dir,dir_entry)):
            if not IsExclude(dir_entry):
                curr_files.append(dir_entry)
        else:
            curr_sub_dirs.append(dir_entry)

    index_item_template = '- [${index_name}](${index_url})'
    for file_item in curr_files:
        file_name, file_subfix = file_item.split('.')
        index_item = index_item_template.replace('${index_name}', file_name)\
            .replace('${index_url}', dir + '/' + file_item)
        index_file.write(index_item)
        index_file.write('\n')
    
    for sub_dir in curr_sub_dirs:
        UpdateSummaryInner(dir + "/" + sub_dir, index_file, depth+1)

# 目前只支持一层子目录
def UpdateIndex(dir, index_file_name):
    index_file = open(index_file_name, 'w')
    UpdateIndexInner(dir, index_file)
    index_file.close()

def UpdateSummary(dir, summary_file_name):
    summary_file = open(summary_file_name, 'w')
    top_str = '''# Summary\n[目录](./目录.md)\n'''
    summary_file.write(top_str)
    UpdateSummaryInner(dir, summary_file)
    summary_file.close()

if __name__ == '__main__':
    UpdateIndex(".", "目录.md")
    UpdateSummary(".", 'SUMMARY.md')